package com.privated.work.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.privated.work.common.Result;
import com.privated.work.entity.BusinessFinal;
import com.privated.work.entity.User;
import com.privated.work.service.BusinessFinalService;
import com.privated.work.service.UserService;
import com.privated.work.utils.FileUtil;
import com.privated.work.utils.ResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Consumer;

@Controller
@RequestMapping("bussiness")
public class BussinessController {

    @Autowired
    private UserService userService;

    @Autowired
    private BusinessFinalService businessFinalService;

    @GetMapping("hello")
    public String hello() {
        System.out.println("hello");
        return "hello";
    }

    @PostMapping("upload")
    @ResponseBody
    public Map<String, Object> upload(@RequestParam MultipartFile file) throws IOException {
//        FileUtil.verifyFileFormat(file, "xlsx", "xls");
        System.out.println("upload");
        System.out.println(file);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("message", "success");
        ImportData importData = new ImportData(businessFinalService);
        EasyExcel.read(file.getInputStream(), BusinessFinal.class, importData).sheet().doRead();
        return map;
    }


    @GetMapping("page")
    @ResponseBody
    public Result page(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit,
                       String z7r30, String installationAddress,String accessMode , String majorType1,String majorType2,String majorType3,
                       String nls8f,String s3089 ,String s71q7,String e2i17,String noz7r30,String noinstallationAddress) {
        QueryWrapper<BusinessFinal> queryWrapper = new QueryWrapper();
        if(!"".equals(noz7r30)){
            String[] split = noz7r30.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("z7r30 like '%"+ s +"%' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        if(!"".equals(noinstallationAddress)){
            String[] split = noinstallationAddress.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("installation_address like '%"+ s +"%' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        if(!"".equals(z7r30)){
            String[] split = z7r30.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("z7r30 not like '%"+ s +"%' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        if(!"".equals(installationAddress)){
            String[] split = installationAddress.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("installation_address not like '%"+ s +"%' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);

        }
        if(!"".equals(accessMode)){

            String[] split = accessMode.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("access_mode  like '%"+ s +"%' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);

        }
        if(!"".equals(majorType1)){
            String[] split = majorType1.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("major_type like '%"+ s +"%' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        if(!"".equals(nls8f)){

            String[] split = nls8f.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("nls8f = '"+ s +"' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);

        }
        if(!"".equals(s3089)){

            String[] split = s3089.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("s3089 = '"+ s +"' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        if(!"".equals(s71q7)){
            String[] split = s71q7.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("s71q7 = '"+ s +"' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        if(!"".equals(e2i17)){
            String[] split = e2i17.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("e2i17 = '"+ s +"' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        Page<BusinessFinal> pageData = businessFinalService.page(new Page<>(page, limit), queryWrapper);
        Result result = new Result(0, "success", pageData.getRecords(), pageData.getTotal());
        return result;
    }

    @GetMapping("export")
    public void export(HttpServletResponse response,String z7r30, String installationAddress,String accessMode , String majorType1,String majorType2,String majorType3,
                       String nls8f,String s3089 ,String s71q7,String e2i17,String noz7r30,String noinstallationAddress) throws IOException{
        QueryWrapper<BusinessFinal> queryWrapper = new QueryWrapper();
        if(!"".equals(noz7r30)){
            String[] split = noz7r30.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("z7r30 like '%"+ s +"%' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        if(!"".equals(noinstallationAddress)){
            String[] split = noinstallationAddress.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("installation_address like '%"+ s +"%' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        if(!"".equals(z7r30)){
            String[] split = z7r30.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("z7r30 not like '%"+ s +"%' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        if(!"".equals(installationAddress)){
            String[] split = installationAddress.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("installation_address not like '%"+ s +"%' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);

        }
        if(!"".equals(accessMode)){

            String[] split = accessMode.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("access_mode  like '%"+ s +"%' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);

        }
        if(!"".equals(majorType1)){
            String[] split = majorType1.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("major_type like '%"+ s +"%' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        if(!"".equals(nls8f)){

            String[] split = nls8f.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("nls8f = '"+ s +"' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);

        }
        if(!"".equals(s3089)){

            String[] split = s3089.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("s3089 = '"+ s +"' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        if(!"".equals(s71q7)){
            String[] split = s71q7.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("s71q7 = '"+ s +"' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        if(!"".equals(e2i17)){
            String[] split = e2i17.split(",");
            StringBuffer sql = new StringBuffer();
            sql.append(" (");
            for (String s : split) {
                sql.append("e2i17 = '"+ s +"' or ");
            }
            int or = sql.lastIndexOf("or");
            String sqlString = sql.substring(0,or);
            sqlString = sqlString +")";
            queryWrapper.apply(sqlString);
        }
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()) , "UTF-8") + ".xlsx");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        List<BusinessFinal> businessFinals = businessFinalService.queryAll(queryWrapper);
        EasyExcel.write(response.getOutputStream(), BusinessFinal.class).sheet("数据").doWrite(businessFinals);

    }


    @GetMapping("delete")
    @ResponseBody
    public Result delete(){
        businessFinalService.deleteAll();
        return ResultUtils.success();
    }

    /**
     * 功能：Java读取txt文件的内容
     * 步骤：1：先获得文件句柄
     * 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
     * 3：读取到输入流后，需要读取生成字节流
     * 4：一行一行的输出。readline()。
     * 备注：需要考虑的是异常情况
     *
     * @param filePath
     */
    public static void readTxtFile(String filePath) {
        try {
            String encoding = "UTF-8";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                String annotaTion = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
//                    if(lineTxt.startsWith("    * ")){
//                        annotaTion = "    @ExcelProperty(\""+lineTxt.substring(lineTxt.lastIndexOf(" ") + 1,lineTxt.length())+"\")";
//                    }
//                    if("    */".equals(lineTxt)){
//                        System.out.println(lineTxt);
//                        System.out.println(annotaTion);
//                    }else {
//                        System.out.println(lineTxt);
//                    }
                    //{field: 'workOrder', title: '工单流水号'}
//                    if(lineTxt.startsWith("    * ")){
//                        annotaTion = lineTxt.substring(lineTxt.lastIndexOf(" ") + 1,lineTxt.length());
//                    }
//                    if(lineTxt.startsWith("    private")){
//                        String[] split = lineTxt.split(" ");
//                        String s = split[split.length - 1];
//                        s = s.substring(0,s.length() - 1);
////                        System.out.println(s);
//                        System.out.println("{field: '"+s+"', title: '"+annotaTion+"'},");
//                    }
                    System.out.println(lineTxt.replaceAll("NULL","''"));
//                    System.out.println(annotaTion);
//                    System.out.println(lineTxt);
                }
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }


    /**
     * 文件数据写入（如果文件夹和文件不存在，则先创建，再写入）
     *
     * @param filePath
     * @param content
     * @param flag     true:如果文件存在且存在内容，则内容换行追加；false:如果文件存在且存在内容，则内容替换
     */
    public static String fileLinesWrite(String filePath, String content, boolean flag) {
        String filedo = "write";
        FileWriter fw = null;
        try {
            File file = new File(filePath);
            //如果文件夹不存在，则创建文件夹
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {//如果文件不存在，则创建文件,写入第一行内容
                file.createNewFile();
                fw = new FileWriter(file);
                filedo = "create";
            } else {//如果文件存在,则追加或替换内容
                fw = new FileWriter(file, flag);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        PrintWriter pw = new PrintWriter(fw);
        pw.println(content);
        pw.flush();
        try {
            fw.flush();
            pw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filedo;
    }


    /**
     * 读取文件，用于文件回显到页面
     *
     * @param url 文件路径 + 文件名
     * @return string 属性
     */
    public static String readFile(String url) {
        BufferedReader br = null;
        String file = "";
        try {
            br = new BufferedReader(new FileReader(url));    // 读取文件

            String line = null;
            while ((line = br.readLine()) != null) {    // 按行读取
                if (StringUtils.isNotBlank(line)) {
                    file += line + ";";
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    //生成随机用户名，数字和字母组成,
    public static String getStringRandom(int length) {
        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        if (val.startsWith("0") || val.startsWith("1") || val.startsWith("2") || val.startsWith("3") || val.startsWith("4") || val.startsWith("5") || val.startsWith("6") || val.startsWith("7") || val.startsWith("8") || val.startsWith("9")) {
            return getStringRandom(length);
        }
        return val;
    }

    public static void main(String[] args) {
//        System.out.println(getStringRandom(5));
        readTxtFile("D:\\coding\\Java\\IDEA\\workspace\\private_work\\万恶的字段.txt");
//        readTxtFile("D:\\coding\\Java\\IDEA\\workspace\\private_work\\JavaBean.txt");
    }

}
